import axios from 'axios'

// create an axios instance
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  // process.env.VUE_APP_BASE_API, // url = base url + request url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // if (store.getters.token) {
    config.headers['X-Token'] = 'token'
    // }
    return config
  },
  error => {
    // do something with request error
    console.error(error, 'error:request-error') // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code !== 20000) {
      console.error(res.message || 'Error', 'success:response-error')
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    console.error(error, 'error:response-error') // for debug
    return Promise.reject(error)
  }
)

export default service
